<template>
  <!--基础信息-->
  <div style="width: 100%" v-show="show">
    <el-collapse v-model="activeName">
      <el-collapse-item title="基本信息" name="1">
        <el-form
          ref="form"
          :disabled="disabled"
          size="small"
          :rules="rulesCom"
          :model="formDataAll"
          label-width="130px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="中文名称" prop="nameCn">
                <el-input
                  placeholder="请输入"
                  v-model="formDataAll.nameCn"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="编码标识" prop="name">
                <div
                  v-if="dialogType === 'add'"
                  class="selfInput"
                  :class="dialogType !== 'add' ? 'disabledSelfInput' : ''"
                >
                  <span>{{ tableNamePrefix }}</span>
                  <el-input
                    v-model="formDataAll.name"
                    :disabled="dialogType !== 'add'"
                    placeholder="请输入小写字母、下划线、数字"
                    @input="
                      formDataAll.tableName = tableNamePrefix + formDataAll.name
                    "
                  >
                  </el-input>
                </div>
                <el-input
                  :disabled="dialogType !== 'add'"
                  v-else
                  v-model="formDataAll.name"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="英文名称">
                <el-input
                  placeholder="请输入"
                  v-model="formDataAll.nameEn"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="父模型" prop="parentName">
                <el-select-tree
                  :value.sync="formDataAll.parentName"
                  :disabled="dialogType !== 'add'"
                  :options="parentIdList()"
                ></el-select-tree>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否抽象" prop="abstractFlag">
                <el-radio-group
                  v-model="formDataAll.abstractFlag"
                  :disabled="disabledTableAttr"
                  @change="(v) => relevanceTableName(v, 'abstractFlag')"
                >
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!--实体模型-->
              <el-form-item v-if="temp == 1" label="模型类型" prop="type">
                <el-select style="width: 100%" v-model="formDataAll.type">
                  <template v-for="item in modelTypeList()">
                    <el-option
                      :key="item.oid"
                      :value="item.value"
                      :label="item.name"
                    ></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <!--关系实体-->
              <el-form-item v-else label="关系类型" prop="refType">
                <el-select style="width: 100%" v-model="formDataAll.refType">
                  <template v-for="item in typeList">
                    <el-option
                      :key="item.oid"
                      :value="item.value"
                      :label="item.name"
                    ></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="表名" prop="tableName">
                <el-input
                  class="prefix"
                  v-model="formDataAll.tableName"
                  :disabled="
                    formDataAll.abstractFlag === 1 ? true : disabledTableAttr
                  "
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存储到父模型表">
                <el-radio-group
                  v-model="formDataAll.whetherStoredToParent"
                  :disabled="
                    formDataAll.abstractFlag === 1 ? true : disabledTableAttr
                  "
                  @change="
                    (v) => relevanceTableName(v, 'whetherStoredToParent')
                  "
                >
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="英文描述">
                <el-input
                  placeholder="请输入"
                  v-model="formDataAll.describeEn"
                  show-word-limit
                  maxlength="1000"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="中文描述" prop="describeCn">
                <el-input
                  placeholder="请输入"
                  v-model="formDataAll.describeCn"
                  show-word-limit
                  maxlength="1000"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="temp === '1'">
            <!--            <el-col :span="12">
                          <el-form-item label="是否Final" prop="whetherFinal">
                            <el-radio-group v-model="formDataAll.whetherFinal" @change="changeWhetherFinal">
                              <el-radio :label="1">是</el-radio>
                              <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                          </el-form-item>
                        </el-col>-->
            <el-col
              :span="12"
              v-if="
                formDataAll.abstractFlag === 1
                  ? false
                  : formDataAll.whetherStoredToParent !== 1
              "
            >
              <el-form-item label="快速扩展" prop="whetherFastExtend">
                <el-radio-group v-model="formDataAll.whetherFastExtend">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="temp == 1">
            <el-col :span="12">
              <el-form-item label="标签">
                <el-select
                  style="width: 100%"
                  filterable
                  multiple
                  v-model="formDataAll.labelIdList"
                >
                  <template v-for="{ name, oid } in tagList">
                    <el-option :label="name" :value="Number(oid)"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图标">
                <avue-input-icon
                  v-model="formDataAll.icon"
                  :icon-list="iconList"
                  :modal-append-to-body="false"
                  placeholder="图标"
                ></avue-input-icon>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="temp == 2">
            <el-col :span="12">
              <el-form-item label="是否树形" prop="isTree">
                <el-radio-group v-model="formDataAll.isTree">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否联动修改" prop="isGanged">
                <el-radio-group v-model="formDataAll.isGanged">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="temp == 2">
            <el-col :span="12">
              <el-form-item label="From实体" prop="fromTypeNameList">
                <el-select-tree
                  :options="fromToTree"
                  :multiple="true"
                  :value.sync="formDataAll.fromTypeNameList"
                ></el-select-tree>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="To实体" prop="toTypeNameList">
                <el-select-tree
                  :options="fromToTree"
                  :multiple="true"
                  :value.sync="formDataAll.toTypeNameList"
                ></el-select-tree>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item
        title="关系结构"
        name="3"
        v-if="
          temp == 2 &&
          formDataAll.fromTypeNameList.length > 0 &&
          formDataAll.toTypeNameList.length > 0
        "
      >
        <el-form
          ref="form2"
          :disabled="disabled"
          size="small"
          :rules="rulesCom"
          :model="formDataAll"
          label-width="130px"
        >
          <el-row>
            <el-col :span="23">
              <el-form-item label="是否排序" prop="referenceWhetherSort">
                <el-radio-group v-model="formDataAll.referenceWhetherSort">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="20" v-if="formDataAll.referenceWhetherSort === 1">
              <el-form-item label="添加排序">
                <el-tree
                  :data="sortData"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                  :render-content="renderContent"
                >
                </el-tree>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="功能列表" name="2">
        <avue-crud
          :option="{ ...baseInfoOption, selection: !disabled }"
          @selection-change="(v) => (selection = v)"
          :data="[...extendsData, ...formDataAll.functionInterfaceList]"
          ref="crud"
        >
          <template slot="extendsFlag" slot-scope="{ row }">
            <i
              style="font-size: 16px"
              :class="row.extendsFlag === 1 ? 'el-icon-check' : 'el-icon-close'"
            ></i>
          </template>

          <template slot="menuLeft">
            <el-button
              size="small"
              type="primary"
              :disabled="disabled"
              @click="
                $refs['gdcd'].open(
                  [...formDataAll.functionInterfaceList, ...extendsData],
                  extendsData
                )
              "
            >
              添加
            </el-button>
            <el-button size="small" :disabled="disabled" @click="remove"
              >移除</el-button
            >
          </template>
        </avue-crud>
      </el-collapse-item>
    </el-collapse>
    <get-data-common-dialog
      title="选择功能"
      ref="gdcd"
      :param="{ type: 2 }"
      url="/api/manager-api/mx-interface/workingPage"
      :column="EntityInterfaceOption.column"
      @addToList="addToList"
    >
    </get-data-common-dialog>
    <el-dialog
      :visible.sync="visible"
      destroy-on-close
      title="新增关系结构"
      width="500px"
      modal-append-to-body
      append-to-body
    >
      <div style="width: 60%; height: 200px" v-if="visible">
        <el-select v-model="addTreeData">
          <template v-for="{ nameCn, name } in slectedData">
            <el-option :label="nameCn" :value="name" :key="name"></el-option>
          </template>
        </el-select>
      </div>
      <div slot="footer" style="text-align: right">
        <el-button size="small" @click="confirmData" type="primary"
          >确定</el-button
        >
        <el-button size="small" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import iconList from "@/config/iconList";

import * as entity from "@/api/modulManage/entity";
import * as relation from "@/api/modulManage/relation";
import GetDataCommonDialog from "@/views/DMDComponent/getDataCommonDialog.vue";
import ElSelectTree from "@/components/el-select-tree.vue";

import index from "./index";
import { mapGetters } from "vuex";
import { getDic } from "@/api/common";
let id = 1000;
export default {
  name: "baseInfo",
  components: { ElSelectTree, GetDataCommonDialog },
  inject: [
    "baseInfoOption",
    "EntityInterfaceOption",
    "parentIdList",
    "modelTypeList",
    "temp",
    "saveError",
  ],
  mixins: [index],
  data() {
    return {
      visible: false,
      currentData: {},
      addTreeData: "",
      slectedData: [],
      sortData: [
        {
          id: 0,
          label: "根节点",
          children: [],
        },
      ],
      activeName: ["1", "2"],

      rules: {
        tableName: [
          { required: true, message: "请输入表名称", trigger: "blur" },
          {
            pattern: "^[a-z][a-z0-9_]{1,29}$",
            message: "请输入正确格式表名称",
          },
        ],
        nameCn: [
          { required: true, message: "请输入中文名称", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入编码标识", trigger: "blur" },
          { pattern: "^[a-z][a-z0-9_]{1,29}$", message: "请输入正确编码标识" },
        ],
        parentName: [
          { required: true, message: "请选择父模型", trigger: "change" },
        ],
        abstractFlag: [
          { required: true, message: "请选择是否抽象", trigger: "change" },
        ],
        describeCn: [
          { required: true, message: "请输入中文描述", trigger: "blur" },
        ],
      },

      rules_: {
        fromTypeNameList: [
          { required: true, message: "请选择From实体", trigger: "change" },
        ],
        toTypeNameList: [
          { required: true, message: "请选择To实体", trigger: "change" },
        ],
        isTree: [
          { required: true, message: "请选择是否树形", trigger: "change" },
        ],
        isGanged: [
          { required: true, message: "请选择是否联动修改", trigger: "change" },
        ],
        refType: [
          { required: true, message: "请选择模型类型", trigger: "change" },
        ],
      },

      rules__: {
        type: [
          { required: true, message: "请选择模型类型", trigger: "change" },
        ],
        whetherFinal: [
          { required: true, message: "请选择是否Final", trigger: "change" },
        ],
        whetherFastExtend: [
          { required: true, message: "请选择是否快速扩展", trigger: "change" },
        ],
      },

      selection: [],

      iconList: iconList,

      typeList: [],
      tagList: [],

      extendsData: [],

      fromToTree: [],
    };
  },
  computed: {
    ...mapGetters(["applicationList"]),
    tableNamePrefix() {
      let appId = localStorage.getItem("appId");
      let name = this.applicationList.filter((i) => appId === i.oid)[0].name;
      return name + "_";
    },
    disabledTableAttr() {
      return this.dialogType === "add"
        ? false
        : !(this.ROW.state === 0 && this.ROW.majorVersion === "A");
    },
    rulesCom() {
      if (this.temp == 1) {
        return { ...this.rules, ...this.rules__ };
      }
      return { ...this.rules, ...this.rules_ };
    },
  },
  methods: {
    closeDialog() {
      this.visible = false;
    },
    confirmData() {
      const [selected] = this.slectedData.filter(
        (v) => v.name === this.addTreeData
      );
      const newChild = {
        id: selected.oid,
        label: selected.nameCn,
        name: selected.name,
        children: [],
      };
      this.currentData.children.push(newChild);
      this.visible = false;
      this.formDataAll.referenceSortJson = JSON.stringify(this.sortData);
    },
    flatData(arr) {
      let result = [];
      for (let item of arr) {
        var res = JSON.parse(JSON.stringify(item));
        delete res["children"];
        result.push(res);
        if (item.children instanceof Array && item.children.length > 0) {
          result = result.concat(this.flatData(item.children));
        }
      }
      return result;
    },

    getFromToData() {
      const newData = [
        ...this.formDataAll.fromTypeNameList,
        ...this.formDataAll.toTypeNameList,
      ];
      const fromToData = [...new Set(newData)].filter(
        (v) => v !== "typeObject"
      ); // 排除基类
      const flatTree = this.flatData(this.fromToTree);
      return flatTree.filter((v) => fromToData.indexOf(v.name) > -1);
    },
    append(data) {
      if (!data.children) {
        this.$set(data, "children", []);
      }
      this.addTreeData = "";
      this.slectedData = this.getFromToData();
      this.visible = true;
      this.currentData = data;
      // data.children.push(newChild);
    },

    removeNode(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.append(data)}
            >
              添加
            </el-button>
            {data.id !== 0 && (
              <el-button
                size="mini"
                type="text"
                on-click={() => this.removeNode(node, data)}
              >
                删除
              </el-button>
            )}
          </span>
        </span>
      );
    },
    changeWhetherFinal(v) {
      if (v === 0) {
        this.formDataAll.whetherFastExtend = 0;
      }
    },
    async save() {
      let f = await this.$refs["form"].validate();
      return new Promise(async (resolve, reject) => {
        if (f) {
          resolve(this.tableNamePrefix);
        } else {
          reject();
        }
      });
    },
    remove() {
      let ids = this.selection.map((i) => i.oid);
      this.formDataAll.functionInterfaceList =
        this.formDataAll.functionInterfaceList.filter(
          (i) => !ids.includes(i.oid)
        );
    },
    addToList(list) {
      let ids = this.extendsData.map((i) => i.oid);
      this.formDataAll.functionInterfaceList = list.filter(
        (i) => !ids.includes(i.oid)
      );
      this.$refs["gdcd"].close();
    },
    getTagList() {
      entity.tagList().then((res) => {
        this.tagList = res.data.data;
      });
    },
    relevanceTableName(v, type) {
      if (this.formDataAll.abstractFlag === 1) {
        this.formDataAll.whetherFastExtend = 0;
      } else {
        if (this.formDataAll.whetherStoredToParent === 1) {
          this.formDataAll.whetherFastExtend = 0;
        }
      }
      if (type === "whetherStoredToParent") {
        if (this.formDataAll.abstractFlag === 1) {
          return;
        }
      }

      if (v === 1) {
        this.$refs.form.clearValidate(["tableName"]);
        this.formDataAll.tableName = "";
      }
      if (v === 0 && this.formDataAll.name) {
        this.formDataAll.tableName =
          (this.dialogType === "add" ? this.tableNamePrefix : "") +
          this.formDataAll.name;
      }
    },
    getExtendsData() {
      entity
        .extends_data({
          type: "2",
          typeName: this.formDataAll.parentName,
          refType: this.temp,
        })
        .then((res) => {
          res.data.data.forEach((i) => {
            i.extendsFlag = 1;
          });
          this.extendsData = this.formDataAll.extendsData = res.data.data;
          let list = JSON.parse(
            JSON.stringify(this.formDataAll.functionInterfaceList)
          );
          let ids = this.extendsData.map((i) => i.oid);
          this.formDataAll.functionInterfaceList = list.filter(
            (i) => !ids.includes(i.oid)
          );

          this.$refs["crud"].refreshTable();
        });
    },
    getFromTo() {
      relation.from_to().then((res) => {
        this.fromToTree = res.data.data;
      });
    },
    getTypeList() {
      getDic("refenrenceEnum").then((res) => {
        this.typeList = res.data.data;
      });
    },
  },
  mounted() {
    this.getTagList();
    this.getFromTo();
    this.getTypeList();
  },
  watch: {
    "formDataAll.referenceSortJson": {
      handler(v) {
        if (v) {
          this.sortData = JSON.parse(v)
        }
      },
      deep: true,
      immediate: true,
    },
    "formDataAll.abstractFlag": {
      handler(v) {
        if (v === 1) {
          this.rules.tableName[0].required = false;
        }
        if (v === 0 && this.formDataAll.whetherStoredToParent === 0) {
          this.rules.tableName[0].required = true;
        }
        if (this.temp == "2") {
          this.rules_.fromTypeNameList[0].required = v !== 1;
          this.rules_.toTypeNameList[0].required = v !== 1;
        }
      },
      deep: true,
      immediate: true,
    },
    "formDataAll.whetherStoredToParent": {
      handler(v) {
        if (v === 1) {
          this.rules.tableName[0].required = false;
        }

        if (this.formDataAll.abstractFlag === 1) {
          this.rules.tableName[0].required = false;
        }

        if (v === 0 && this.formDataAll.abstractFlag === 0) {
          this.rules.tableName[0].required = true;
        }
      },
      deep: true,
      immediate: true,
    },
    "formDataAll.parentName": {
      handler(v) {
        if (v) {
          this.getExtendsData();
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="scss">
.selfInput {
  border: 0.01rem solid #dcdfe6;
  color: #606266;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: nowrap;
  padding: 0 15px;
  border-radius: 4px;
  background: #fff;

  .el-input {
    .el-input__inner {
      padding: 0;
      border-radius: 0;
      border: none;
    }
  }
}

.disabledSelfInput {
  background: #f5f7fa;
}
</style>
